from sanic import Sanic
from sanic.response import HTTPResponse,text
from sanic.request import Request

app = Sanic.get_app("myapp")

@app.get("/print")
async def hello_print(request):
    return text("Hello print.")

#异步提升性能
@app.get("/async")
async def async_handler(request):
    # await asyncio.sleep(0.1)
    return text("Done.")

#使用类型注解
@app.get("/typed")
async def typed_handler(request: Request) -> HTTPResponse:
    return text("Done.")
# @app.get("/")
# @app.route('/test', methods=["POST", "PUT","GET"])
# async def hello(request):
#     return text("Hello, world.")

#基于类视图
'''class SimpleView(HTTPMethodView):

  def get(self, request):
      return text("I am get method")

  # You can also use async syntax
  def post(self, request):
      return text("I am post method")

  def put(self, request):
      return text("I am put method")

  def patch(self, request):
      return text("I am patch method")

  def delete(self, request):
      return text("I am delete method")

app.add_route(SimpleView.as_view(), "/")'''


#解析请求对象
# print(request.json)
# print(request.body)
# print(request.form)
# request.form.get("foo")
# request.form.getlist("foo")
# request.files
# request.files.get("my_file")
# request.files.getlist("my_file")


#请求参数
# >>> print(request.args)
# {'key1': ['val1', 'val3'], 'key2': ['val2']}
#
# >>> print(request.args.get("key1"))
# val1
#
# >>> print(request.args.getlist("key1"))
# ['val1', 'val3']
#
# >>> print(request.query_args)
# [('key1', 'val1'), ('key2', 'val2'), ('key1', 'val3')]
#
# >>> print(request.query_string)
# key1=val1&key2=val2&key1=val3

# return text(
#     f"{request.remote_addr} connected to {request.url_for('test')}\n"
#     f"Forwarded: {request.forwarded}\n"
# )


# request.ctx 对象是存储请求相关信息的地方
# request.ctx.user

# 数据库
# app.ctx.db = Database()
#
#

# @app.route("/fwd")
# async def forwarded(request):
#     return json(
#         {
#             "remote_addr": request.remote_addr,
#             "scheme": request.scheme,
#             "server_name": request.server_name,
#             "server_port": request.server_port,
#             "forwarded": request.forwarded,
#         }
#     )

